package com.fujitsu.cn.fnst.dao;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fujitsu.cn.fnst.common.ReflectUtils;
import com.fujitsu.cn.fnst.entiy.Meeting;
import com.fujitsu.cn.fnst.entiy.MeetingBook;
import com.fujitsu.cn.fnst.model.MeetingModel;
import com.fujitsu.cn.fnst.service.MeetingService;

@Repository
public class MeetingBookDao extends BaseDao<MeetingBook> {
    @Resource
    private MeetingService meetingsService;

    public MeetingModel getMeetingState(int meetingId) {
        Meeting meeting = meetingsService.find(meetingId);
        return getMeetingState(meeting);
    }

    public MeetingModel getMeetingState(Meeting meeting) {
        if (meeting == null) {
            return null;
        }
        MeetingModel model = new MeetingModel();
        try {
            ReflectUtils.copy(meeting, model);
        } catch (IllegalAccessException | InvocationTargetException
                | NoSuchMethodException e) {
            e.printStackTrace();
        }
        Session session = getSession();
        Criteria criteria = session.createCriteria(MeetingBook.class);
        Date now = new Date();
        criteria.add(Restrictions.eq("meetingId", meeting.getId()))
                .add(Restrictions.le("bookStartTime", now))
                .add(Restrictions.ge("bookEndTime", now));
        boolean used = query(criteria).size() >= 1;
        model.setUsed(used);
        return model;
    }

    public List<MeetingModel> getMeetingState(String where, String order) {
        List<MeetingModel> models = new ArrayList<MeetingModel>();
        List<Meeting> meetings = meetingsService.findByWhereAndOrder(where,
                order);
        for (Meeting meetings2 : meetings) {
            MeetingModel model = getMeetingState(meetings2);
            models.add(model);
        }
        return models;
    }

    public String timeModel(String date, String beginTime, String endTime,
            String amount) throws ParseException {
        String dateBegin = date + " " + beginTime.toUpperCase();
        String dateEnd = date + " " + endTime.toUpperCase();
        Date beginDate = getDateformat().parse(dateBegin);
        Date endDate = getDateformat().parse(dateEnd);
        int amountInt = Integer.parseInt(amount.trim());
        return "hahh";
    }

}
